/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.delivery.multishop.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.yami.shop.bean.app.dto.MyOrderDto;
import com.yami.shop.bean.enums.OfflineHandleEventType;
import com.yami.shop.bean.model.OfflineHandleEvent;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.Station;
import com.yami.shop.bean.param.OfflineHandleEventAuditParam;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.delivery.common.model.OrderSelfStation;
import com.yami.shop.delivery.common.service.OrderSelfStationService;
import com.yami.shop.security.common.enums.SysTypeEnum;
import com.yami.shop.security.common.manager.PasswordManager;
import com.yami.shop.security.common.manager.TokenStore;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.OfflineHandleEventService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.OrderVirtualInfoService;
import com.yami.shop.service.StationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * 自提点
 *
 * @author YXF
 * @date 2020-04-23 15:18:29
 */
@RestController
@AllArgsConstructor
@RequestMapping("/admin/station")
@Api(tags = "商家端自提接口")
public class StationController {

    private final StationService stationService;

    private final OrderSelfStationService orderSelfStationService;

    private final OfflineHandleEventService offlineHandleEventService;

    private final OrderService orderService;

    private final OrderVirtualInfoService orderVirtualInfoService;

    private final PasswordEncoder passwordEncoder;

    private final TokenStore tokenStore;

    private final PasswordManager passwordManager;

    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('admin:station:page')")
    @ApiOperation(value = "分页查询自提点信息")
    public ServerResponseEntity<IPage<Station>> getStatonPage(PageParam<Station> page, Station station) {
        station.setShopId(SecurityUtils.getShopUser().getShopId());
        return ServerResponseEntity.success(stationService.getPage(page, station));
    }

    @GetMapping("/info/{stationId}")
    @ApiOperation(value = "通过id查询自提点")
    @ApiImplicitParam(name = "stationId", value = "自提点id", required = true, dataType = "Long")
    public ServerResponseEntity<Station> getById(@PathVariable("stationId") Long stationId) {
        Station station = stationService.getStationInfoById(stationId);
        if (!Objects.equals(SecurityUtils.getShopUser().getShopId(), station.getShopId())) {
            throw new YamiShopBindException("yami.no.auth");
        }
        return ServerResponseEntity.success(station);
    }

    @PostMapping
    @PreAuthorize("@pms.hasPermission('admin:station:save')")
    @ApiOperation(value = "新增自提点")
    public ServerResponseEntity<Boolean> save(@RequestBody @Valid Station station) {
        station.setShopId(SecurityUtils.getShopUser().getShopId());
        station.setAccount(null);
        station.setPassword(null);
        stationService.insertStation(station);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @PreAuthorize("@pms.hasPermission('admin:station:update')")
    @ApiOperation(value = "修改自提点")
    public ServerResponseEntity<Boolean> updateById(@RequestBody @Valid Station station) {
        station.setAccount(null);
        station.setPassword(null);
        Long shopId = SecurityUtils.getShopUser().getShopId();
        station.setShopId(shopId);
        stationService.updateStation(station);
        return ServerResponseEntity.success();
    }

    @SysLog("删除自提点")
    @DeleteMapping("/{stationId}")
    @ApiOperation(value = "通过id删除自提点")
    @ApiImplicitParam(name = "stationId", value = "自提点id", required = true, dataType = "Long")
    @PreAuthorize("@pms.hasPermission('admin:station:delete')")
    public ServerResponseEntity<Boolean> removeById(@PathVariable Long stationId) {
        stationService.removeStationById(stationId);
        tokenStore.deleteAllToken(SysTypeEnum.STATION.value().toString(),stationId.toString());
        return ServerResponseEntity.success();
    }

    @PutMapping("/changeAccountInfo")
    @PreAuthorize("@pms.hasPermission('admin:station:changeAccountInfo')")
    @ApiOperation(value = "账号密码设置")
    public ServerResponseEntity<Void> changeAccountInfo(@RequestBody @Valid Station station) {
        String decryptPassword = passwordManager.decryptPassword(station.getPassword());
        station.setPassword(passwordEncoder.encode(decryptPassword));
        stationService.changeAccountInfo(station);
        tokenStore.deleteAllToken(SysTypeEnum.STATION.value().toString(),station.getStationId().toString());
        return ServerResponseEntity.success();
    }

    @GetMapping("/checkStationAccount")
    @ApiOperation(value = "校验账号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "stationId", value = "自提点id", dataType = "Long"),
            @ApiImplicitParam(name = "account", value = "自提点账号", dataType = "String")
    })
    public ServerResponseEntity<Boolean> checkStationAccount(@RequestParam("stationId") Long stationId, @RequestParam("account") String account) {
        int count = stationService.getCountByAccount(account, stationId);
        if (count > 0) {
            return ServerResponseEntity.success(false);
        }
        return ServerResponseEntity.success(true);
    }

    @GetMapping("/getOfflineHandleEventByStatonId/{stationId}")
    @ApiOperation(value = "通过自提点id获取下线信息")
    @ApiImplicitParam(name = "stationId", value = "自提点id", required = true, dataType = "Long")
    public ServerResponseEntity<OfflineHandleEvent> getOfflineHandleEventByStatonId(@PathVariable("stationId") Long stationId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.STATION.getValue(), stationId);
        return ServerResponseEntity.success(offlineHandleEvent);
    }

    @PostMapping("/auditApply")
    @ApiOperation(value = "下线自提点提交审核")
    @PreAuthorize("@pms.hasPermission('admin:station:auditApply')")
    public ServerResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Station station = stationService.getById(offlineHandleEventAuditParam.getHandleId());
        if (station == null) {
            // 未找到该自提点信息
            throw new YamiShopBindException("yami.station.no.find");
        }
        stationService.auditApply(offlineHandleEventAuditParam.getEventId(), offlineHandleEventAuditParam.getHandleId(), offlineHandleEventAuditParam.getReapplyReason());
        return ServerResponseEntity.success();
    }

    @GetMapping("/getOrderItemAndStationInfo")
    @ApiOperation(value = "获取提货订单详情")
    public ServerResponseEntity<OrderSelfStation> getOrderItemAndStationInfo(@RequestParam("orderNumber") String orderNumber) {
        Order order = orderService.getOrderAndOrderItemByOrderNumber(orderNumber);
        OrderSelfStation orderSelfStation = orderSelfStationService.getOne(new LambdaQueryWrapper<OrderSelfStation>().eq(OrderSelfStation::getOrderNumber, orderNumber));
        orderService.getOrderItemRefundStatus(order);
        orderSelfStation.setOrderItems(order.getOrderItems());
        return ServerResponseEntity.success(orderSelfStation);
    }

    @PutMapping("/changeStatusAndOrderStation")
    @ApiOperation(value = "自提订单发货")
    @PreAuthorize("@pms.hasPermission('admin:station:orderItemsDelivery')")
    public ServerResponseEntity<Void> changeStatusAndOrderStation(@RequestBody OrderSelfStation orderSelfStation) {
        List<String> orderNumberList = Lists.newArrayList();
        orderNumberList.add(orderSelfStation.getOrderNumber());
        orderService.orderStationByOrderNumber(orderNumberList, null, orderSelfStation.getStationId());
        return ServerResponseEntity.success();
    }

    @PutMapping("/orderWriteOffByOrderNumber")
    @ApiOperation(value = "用户虚拟商品订单核销操作", notes = "用户虚拟商品订单核销操作")
    @PreAuthorize("@pms.hasPermission('order:virtual:update')")
    public ServerResponseEntity<Boolean> orderWriteOffByOrderNumber(@RequestBody MyOrderDto myOrderDto) {
        String orderNumber = myOrderDto.getOrderNumber();
        Long shopId = SecurityUtils.getShopUser().getShopId();
        if (StrUtil.isBlank(orderNumber)) {
            // 订单不存在
            throw new YamiShopBindException("yami.order.no.exist");
        }
        Order orderDb = orderService.getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNumber, orderNumber)
                .eq(Order::getShopId, shopId)
                .eq(Order::getOrderMold, 1));
        if (Objects.isNull(orderDb)) {
            // 订单不存在
            throw new YamiShopBindException("yami.order.no.exist");
        }
        return ServerResponseEntity.success(orderVirtualInfoService.orderWriteOffByOrderNumber(myOrderDto, orderDb, null));
    }
}
